package com.lfs.Dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.lfs.Entity.ProductEntity;
import com.lfs.Utils.JDBCUtil;

public class ProductDao {
    
	public static boolean ProductAdd(ProductEntity pe) {
		return JDBCUtil.executeUpade
		("INSERT INTO `tb_merchandise` (`name`, `describe`, `number`, `price`, `img`) VALUES (?, ?, ?, ?, ?)"
		,pe.getName(),pe.getDescribe(),pe.getNumber(),pe.getPrice(),pe.getImg());
		
	}
	
    public static  int ProductNum() {
        String sql = "SELECT COUNT(id) as num FROM tb_merchandise";
    	PreparedStatement ps = null;
    	ResultSet rs=null;
    	try {
			 ps =JDBCUtil.getconnection().prepareStatement(sql);
			 rs = ps.executeQuery();
			 while (rs.next()) {
				return rs.getInt("num");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				ps.close();
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return 0;
		
	}
    
	public static List<ProductEntity> ProductSelectAll(int currentPage,int pageCount) {
        return	JDBCUtil.executeQuery("SELECT * FROM `tb_merchandise` LIMIT "+(currentPage-1)*pageCount+","+pageCount+"");	
	}
    
	public static ProductEntity ProductSelect(int id) {
		return  JDBCUtil.executeQuery("SELECT * FROM `tb_merchandise` where id=?", id).get(0);
	}
  
	public static boolean ProductUpate(ProductEntity pe) {
		return JDBCUtil.executeUpade
	("UPDATE `tb_merchandise` SET `name`=?, `describe`=?, `number`=?, `price`=?, `img`=? WHERE (`id`=?) "
	,pe.getName(),pe.getDescribe(),pe.getNumber(),pe.getPrice(),pe.getImg(),pe.getId());
	}
   
	public static boolean ProductDelect(int id) {
		return JDBCUtil.executeUpade("DELETE FROM `tb_merchandise` WHERE (`id`=?)",id);
	}
	
	public static boolean Pvaild(String name) {
		String sql = "SELECT id FROM `tb_merchandise` WHERE `name`= ?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			 ps = JDBCUtil.getconnection().prepareStatement(sql);
			 ps.setString(1, name);
			 rs = ps.executeQuery();
			 return rs.next();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			 try {
				ps.close();
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return false;
		
	}


}
